package com.dong.mcd.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dong.mcd.model.SysUser;
import com.dong.mcd.pub.Constants;

public class LoginInterceptor implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		SysUser user = (SysUser) req.getSession().getAttribute(Constants.CURRENT_USER);
		String requestPath = req.getRequestURI();
		String reqHead = req.getHeader("x-requested-with");
		if (!requestPath.endsWith("login.jsp") && !requestPath.endsWith("login")){
			if (user == null){
				if (reqHead !=null && reqHead.equalsIgnoreCase("XMLHttpRequest")){
					    resp.setContentType("application/json;charset=UTF-8");
					    throw new RuntimeException("{\"error\":true,\"result\":\"登录超时\"}");
				}else{
					req.getRequestDispatcher("/web/login.jsp").forward(req, resp);
				}
			}else{
				chain.doFilter(request, response);
			}
		}else{
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	
}
